package com.jaks.xpense;

import java.util.Calendar;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

import com.jaks.xpense.data.Expenses;
import com.jaks.xpense.utils.Globals;
import com.jaks.xpense.utils.WidgetUtils;

public class XpenseDroidWidget extends AppWidgetProvider {

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);

		RemoteViews updateViews = buildUpdate(context);
		WidgetUtils.updateWidget(context, updateViews);
	}

	@Override
	public void onReceive(Context context, Intent intent) {

		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgethome);

		if (intent.getAction().equals(Globals.UpdateFromActivity)) {
			String today = intent.getExtras().getString(Globals.Today);
			String balance = intent.getExtras().getString(Globals.Balance);

			WidgetUtils.updateView(context, remoteViews, today, balance);
		} else {
			super.onReceive(context, intent);
		}

		WidgetUtils.updateWidget(context, remoteViews);
	}

	private RemoteViews buildUpdate(Context context) {

		Expenses expenses = null;
		RemoteViews remoteViews = null;

		try {
			expenses = new Expenses(context);
			remoteViews = new RemoteViews(context.getPackageName(), R.layout.widgethome);

			String today = Globals.toDateText(Calendar.getInstance());
			double todayTotal = expenses.getTotalAmount(today, today);
			double balance = expenses.getBalance();

			WidgetUtils.updateView(context, remoteViews, Globals.toDecimalText(todayTotal),
			    Globals.toDecimalText(balance));
		} catch (Exception ex) {
		} finally {
			if (expenses != null)
				expenses.close();
		}
		return remoteViews;
	}
}
